package cn.tedu.baking.controller;

import cn.tedu.baking.response.common.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Author：毕龙
 * Date: 2024/8/14 16:41
 */
@RestController
@RequestMapping("/v1/")
public class UploadController {
    //将配置文件中配置的路径注入的属性中
    @Value("${FILE_PATH}")
    private String FILE_PATH;

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //获取文件的名字
        String fileOriginName = file.getOriginalFilename();
        //截取文件的后缀名
        String suffix = fileOriginName.substring(fileOriginName.lastIndexOf('.'));
        //获取uuid+文件后缀名
        String fileNewName= UUID.randomUUID()+suffix;
        //自定义一个时间的格式
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //创建文件路径对象
        File fileDir = new File(FILE_PATH + datePath);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        //文件路径
        String filePutPath = FILE_PATH + datePath + fileNewName;
        //上传文件
        file.transferTo(new File(filePutPath));

        //将图片的路径发送给前端
        return JsonResult.ok(datePath+fileNewName);
    }

    @PostMapping("remove")
    public JsonResult remove(String url){
        new File(FILE_PATH+url).delete();
        return JsonResult.ok();
    }
}
